package com.lab.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.cuitrip.app.MainApplication;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.I118Util;
import com.cuitrip.util.PlatformUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created on 7/16.
 */
public class Utils {

    /**
     * 日期格式
     */
    public static final String DATE_FORMAT_DAY = "yyyy-MM-dd";
    public static final String DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
    public static final String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_MOTH = "MM-dd";

    public static final String DATE_FORMAT_SECOND_M = "yyyy-MM-dd HH:mm:ss.sss";
    public static final String DATE_FORMAT_DAY_Z = "yyyy-MM-dd z";




    @Deprecated
    public static long parseStringToLongTime(String time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, I118Util.getLocale());
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+800"));
        try {
            long result = sdf.parse(time.trim()).getTime();
            LogHelper.e("parseStringToLongTime", time + "|" + result);
            return result;
        } catch (Exception e) {
            return -1;
        }
    }


    static SimpleDateFormat H_M = new SimpleDateFormat("HH:mm", Locale.CHINA);
    static SimpleDateFormat Y_M_D = new SimpleDateFormat(DATE_FORMAT_DAY, Locale.CHINA);
    static SimpleDateFormat Y_M_D_H_M = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);

    static {
        H_M.setTimeZone(TimeZone.getTimeZone("GMT+800"));
        Y_M_D.setTimeZone(TimeZone.getTimeZone("GMT+800"));
        Y_M_D_H_M.setTimeZone(TimeZone.getTimeZone("GMT+800"));
    }


    @Deprecated
    public static String getMsToD(String dateTime) {

        long value = 0;
        try {
            value = Long.parseLong(dateTime);
        } catch (NumberFormatException e) {
            value = parseStringToLongTime(dateTime, DATE_FORMAT_SECOND);
        }
        String result = Y_M_D.format(value);
        return result;
    }

    @Deprecated
    public static String getMsToSeconds(String dateTime) {

        long value = 0;
        try {
            value = Long.parseLong(dateTime);
        } catch (NumberFormatException e) {
            value = parseStringToLongTime(dateTime, DATE_FORMAT_SECOND);
        }
        return Y_M_D_H_M.format(value);
    }

    public static void requestDial(Activity activity, String tele) {
        if (!TextUtils.isEmpty(tele)) {
            try {
                activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + tele)));
            } catch (Exception e) {
//                try {
//                    AlertDialog.Builder builder = MessageUtils.createHoloBuilder(activity);
//                    builder.setMessage(activity.getText(R.string.ct_call_phone_fail) + tele)
//                            .create().show();
//                } catch (Exception e1) {
//                    e1.printStackTrace();
//                }
            }
        } else {
//            MessageUtils.showToast(activity.getString(R.string.ct_null_phone_num));
        }
    }

    public static boolean isAliInstalled() {
        String packageName = "com.eg.android.AlipayGphone";
        final PackageManager packageManager = MainApplication.getInstance().getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    public static boolean isWXInstalled() {
        String packageName = "com.tencent.mm";
        final PackageManager packageManager = MainApplication.getInstance().getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    public static int dp2pixel(int i) {
        return (int) (0.5F + MainApplication.getInstance().getResources().getDisplayMetrics().density * (float) i);
    }

    public static float dp2pixelF(int i) {
        return (0.5F + MainApplication.getInstance().getResources().getDisplayMetrics().density * (float) i);
    }

    public static float px2dp(int i) {
        return (float) i / MainApplication.getInstance().getResources().getDisplayMetrics().density + 0.5f;
    }

    public static HashMap<String, String> sGenderHashMap = new HashMap<>();

    public static void initGenderMap() {
        sGenderHashMap.put(PlatformUtil.getInstance().getString(R.string.ct_male_code), PlatformUtil.getInstance().getString(R.string.filter_option_insider_value_male));
        sGenderHashMap.put(PlatformUtil.getInstance().getString(R.string.ct_gende_non_code), PlatformUtil.getInstance().getString(R.string.value_no_set));
        sGenderHashMap.put(PlatformUtil.getInstance().getString(R.string.ct_female_code), PlatformUtil.getInstance().getString(R.string.filter_option_insider_value_female));
    }

    public static String getGender(String code) {
        if (sGenderHashMap == null || sGenderHashMap.isEmpty()) {
            initGenderMap();
        }
        LogHelper.e("omg", "gender" + code + " |" + sGenderHashMap.containsKey(code.trim()));
        if (sGenderHashMap.containsKey(code.trim())) {
            return sGenderHashMap.get(code.trim());
        }
        return code;
    }

    public static String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
        return line;
    }


    public static String getText(String value, String defaultValue) {
        return TextUtils.isEmpty(value) ? defaultValue : value;
    }

    public static void setTextViewValue(TextView textView, String value, String hint) {
        if (TextUtils.isEmpty(value)) {
            textView.setHint(hint);
        } else {
            textView.setText(value);
        }
    }

    public static void setRightTextViewValue(ItemLayout textView, CharSequence value, CharSequence hint) {
        if (TextUtils.isEmpty(value)) {
            textView.setmRightText(hint);
            textView.setRightTextColor(R.color.ganshi_ded8d7);
        } else {
            textView.setmRightText(value);
            textView.setRightTextColor(R.color.qiaomai_7c706e);
        }
    }

    public static String formatPaypal(String paypal) {
        if (TextUtils.isEmpty(paypal)) {
            return "";
        }
        if (paypal.length() <= 2) {
            return paypal.substring(0, 1) + "*";
        }
        StringBuilder builder = new StringBuilder();
        if (isEmail(paypal)) {
            int index = paypal.lastIndexOf("@");
            if (index >= 0) {
                builder.append(paypal.substring(0, index > 3 ? 3 : index - 1));
                builder.append("***");
                builder.append(paypal.substring(index));
            }
        } else {
            int end = paypal.length() > 3 ? 3 : paypal.length() - 1;
            builder.append(paypal.substring(0, end));
            builder.append("***");
        }
        return builder.toString();
    }

    public static boolean isEmail(String newValue) {
        if (TextUtils.isEmpty(newValue)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
        Matcher matcher = pattern.matcher(newValue);
        return matcher.matches();
    }

    public static void shakeView(View v) {
        Animation animation = AnimationUtils.loadAnimation(v.getContext(), R.anim.shake);
        v.startAnimation(animation);
    }

    public static void startBrowser(Activity activity, String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        activity.startActivity(intent);
    }

    public static void jump(Activity activity, String schemes, String packageName, String url) {
        try {
            activity.startActivity(getIntent(activity,schemes,packageName,url));
        } catch (Exception e) {
        }
    }

    public static Intent getIntent(Context context, String schemes, String packageName, String url) {
        try {
            context.getPackageManager().getPackageInfo(packageName, 0);
            return new Intent(Intent.ACTION_VIEW, Uri.parse(schemes));
        } catch (PackageManager.NameNotFoundException e) {
            return new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        }
    }

    public static void hideSoftInputMethod(Activity activity) {
        InputMethodManager imm= (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()){
                imm.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
            }
    }

    public static String mergeStrings(String[] array, String insert) {
        StringBuilder sb = new StringBuilder();
        for (String string : array) {
            if (sb.length() > 0 && !TextUtils.isEmpty(string)) {
                sb.append(insert);
            }
            if (!TextUtils.isEmpty(string)){
                sb.append(string);
            }
        }
        return sb.toString();
    }
}
